import os
import time
from pathlib import Path

import pytest



@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args):
    return {
        **browser_type_launch_args,
        "headless": False,
        # 使用系统安装的 Google Chrome（包含 Widevine CDM 与更多媒体编解码器）
        "channel": "chrome",
        # 取消 Playwright 默认静音，并放宽自动播放策略，提升首帧可播放概率
        "ignore_default_args": [
            "--mute-audio",
        ],
        "args": [
            "--autoplay-policy=no-user-gesture-required",
        ],
    }


STORAGE_DIR = Path(__file__).parent / "auth"
STORAGE_PATH = STORAGE_DIR / "storage_state.json"
# LOGIN_URL = "https://www.iqiyi.com/iv#/?ver=tesla"
LOGIN_URL = "https://www.iqiyi.com/iv#/personal?ver=tesla"


def _create_storage_state(browser):
    """在首次运行时引导手动登录并保存会话文件。"""
    STORAGE_DIR.mkdir(parents=True, exist_ok=True)
    context = browser.new_context()
    page = context.new_page()
    page.goto(LOGIN_URL)
    print("\n请在已打开的浏览器窗口中完成登录（如扫码/输入账号）。\n将在 90 秒后自动保存会话信息并关闭。\n")
    time.sleep(15)
    context.storage_state(path=str(STORAGE_PATH))
    context.close()


@pytest.fixture(scope="session", autouse=True)
def ensure_login_state(browser):
    """会话前确保存在 storage_state；不存在则引导一次登录创建。"""
    if not STORAGE_PATH.exists():
        _create_storage_state(browser)
    yield


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    """为每个上下文加载已保存的 storage_state，从而复用登录态。"""
    args = {**browser_context_args}
    if STORAGE_PATH.exists():
        args["storage_state"] = str(STORAGE_PATH)
    # 统一语言/时区/UA，提升与手动 Chrome 一致性
    args.update({
        "locale": "zh-CN",
        "timezone_id": "Asia/Shanghai",
        "user_agent": (
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/126.0.0.0 Safari/537.36"
        ),
        # 设置页面可视区域大小（不包括浏览器功能区）
        "viewport": {"width": 1180, "height": 820},
        # 仅模拟渲染比例（DPR），不切换为移动端
        "device_scale_factor": 2,
        "is_mobile": False,
        "has_touch": False,
    })
    return args


# 轻量“隐身”脚本，降低站点对自动化环境的拦截概率
STEALTH_JS = r"""
// 隐藏 webdriver 标记
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
// 伪造语言列表
Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh'] });
// 伪造插件数量
Object.defineProperty(navigator, 'plugins', { get: () => [1,2,3,4,5] });
// 补齐 window.chrome
if (!window.chrome) { window.chrome = { runtime: {} }; }
"""


@pytest.fixture(autouse=True)
def apply_stealth_and_logging(context, page):
    """为上下文注入隐身脚本，并记录页面关键信息以便排查。"""
    try:
        context.add_init_script(STEALTH_JS)
    except Exception:
        pass
    page.on("console", lambda m: print("PAGE LOG:", m.type, m.text))
    page.on("pageerror", lambda e: print("PAGE ERROR:", e))
    page.on("requestfailed", lambda r: print("REQUEST FAILED:", r.url, r.failure))
    yield

